<template>
	<view class="text-df">
		<view class="padding-lg bg-white">
			<view class="text-lg theme-color text-bold">投诉意见</view>
			<view class="margin-top-sm flex-row">
				<view style="width: 150rpx;">地址：</view>
				<view> {{compose.location}}</view>
			</view>
			<view class="margin-top-sm flex-row">
				<view style="width: 150rpx;">详细地址：</view>
				<view> {{compose.fullAddress}}</view>
			</view>
			<view class="margin-top-sm flex-row">
				<view style="width: 150rpx;">发表时间：</view>
				<view> {{compose.createTime}}</view>
			</view>
			<view class="margin-top-sm flex-row">
				<view style="width: 150rpx;">意见内容：</view>
				<view style="width: 65%;height:100px;overflow-y: scroll;" @click="getDetail(compose.content)"> {{compose.content}}</view>
			</view>
			<view class="margin-tb-sm">图片描述：</view>
			<view style="display: flex; flex-wrap: wrap;">
				<image v-for="(item,index) in compose.imageList" :key="index" :src="item.url"
					style="width: 150rpx; height: 150rpx;" mode="aspectFill" class="margin-right-sm margin-top-sm">
				</image>
			</view>
		</view>

		<view class="padding-lg bg-white margin-top-sm">
			<view class="text-lg theme-color text-bold margin-bottom-sm">处理结果</view>

			<u--form labelPosition="left" :model="form" :rules="rules" ref="form" :borderBottom="false">
				<u-form-item label="辖区选择" prop="select" :borderBottom="false" ref="item1" labelWidth="80">
					<u--input v-model="form.select" disabled disabledColor="#ffffff" placeholder="请选择辖区"
						border="none"></u--input>
					<!-- <u-icon slot="right" name="arrow-right"></u-icon> -->
				</u-form-item>
				<u-picker :show="show" ref="uPicker" :columns="columns" @confirm="confirm" @cancel="cancel"
					@change="changeHandler"></u-picker>
				<u-form-item label="问题描述" prop="content" :borderBottom="false" ref="item1" labelWidth="80">
					<u--textarea v-model="form.content" placeholder="问题描述..." count></u--textarea>
				</u-form-item>
				<u-form-item label="上传图片" prop="imageValue" :borderBottom="false" ref="item1" labelWidth="80">
					<uni-file-picker @select="handleSelect" v-model="form.imageValue"
						@delete="deletePic"></uni-file-picker>
				</u-form-item>
			</u--form>
		</view>

		<view style="height: 100px;"></view>

		<view class="flex-row-bt fix-bottom">
			<button hover-class="none" class="login-btn theme-color" style="border: 1px solid #247eff;"
				@click="refresh">重新分配</button>
			<button hover-class="none" class="login-btn theme-bg-color text-white" style=""
				@click="submit()">上传结果</button>
		</view>
	</view>
</template>

<script>
	import {
		getFirstAddress,
		getSecondAddress
	} from '../../api/address_api'
	import {
		sentAddress,
		uploadResults
	} from '../../api/release'
	import config from '../../config'
	import {
		getResultsByAdviseId
	} from '../../api/advise_api.js'

	export default {
		data() {
			return {
				compose: {
					"id": 420,
					"phone": "18979932134",
					"location": "桐田村",
					"fullAddress": "桐田村",
					"firstAddress": "峡山口街",
					"secondAddress": "峡山口街道本级",
					"content": "桐田农民街屋顶搭棚没做水槽， 水直接掉下来，造成2楼外墙湿，里墙发霉",
					"createTime": "2024-04-09 15:47:44",
					"stateCode": 1,
					"state": "待处理",
					"count": 0,
					"rate": 0,
					"imageList": [{
						"id": 876,
						"url": "https://xtianchuang.com/tc/File/2024-04-09/96ad0eac-6f8b-4e7b-909e-9aa6573e4b16.jpg",
						"aid": 420,
						"rid": null
					}],
					"longitude": "113.7984619140625",
					"latitude": "27.57775115966797"
				},

				//级联选择器
				show: false,
				columns: [],
				columnData: [],
				// 加载
				loading: true,
				locationList: [],

				// 处理结果表单
				form: {
					adviseId: '',
					content: '',
					phone: '',
					imgList: [],
					name: '',

					//辖区选择
					select: '',
					firstAddress: '',
					secondAddress: '',

					imageValue: []
				},
				rules: {
					select: {
						type: 'string',
						required: true,
						message: '请选择辖区',
						trigger: ['blur', 'change']
					},
					content: {
						type: 'string',
						required: true,
						message: '请输入问题描述',
						trigger: ['blur', 'change']
					},
					imageValue: {
						type: 'array',
						min: 1,
						required: true,
						message: '请上传图片',
						trigger: ['change']
					}
				},
			}
		},
		onLoad(options) {
			this.form.adviseId = options.id
			//详情
			this.getinfo()
			this.form.phone = uni.getStorageSync('phone')
			this.form.name = uni.getStorageSync('userInfo').name
			this.getFirstAddress()
			this.getSecondAddress(0)
		},
		methods: {
			getDetail(info) {
				uni.showModal({
				    content: info,//模板中提示的内容
				    confirmText:'复制内容',
				    success:(res) => {//点击复制内容的后调函数
						if(res.confirm) {
							let result
							// #ifndef H5
							//uni.setClipboardData方法就是讲内容复制到粘贴板
							uni.setClipboardData({
								data: info,//要被复制的内容
								success:() => {//复制成功的回调函数
									uni.showToast({//提示
										title:'复制成功' 
									})
								}
							});
							// #endif
							
							 // #ifdef H5 
								let textarea = document.createElement("textarea")
								textarea.value = info
								textarea.readOnly = "readOnly"
								document.body.appendChild(textarea)
								textarea.select() // 选中文本内容
								textarea.setSelectionRange(0, info.length) 
								uni.showToast({//提示
									title:'复制成功' 
								})
								result = document.execCommand("copy") 
								textarea.remove()    
							// #endif
						} else {
							console.log('取消')
						}
				    }
				});
			},
			//详情
			getinfo() {
				getResultsByAdviseId(this.form.adviseId).then(res => {
					this.compose = res.data.advise
					console.log(res.data.advise)
					this.form.select = res.data.advise.firstAddress + "/" + res.data.advise.secondAddress
				})
			},
			//获取一级辖区列表
			getFirstAddress() {
				getFirstAddress().then(res => {
					this.locationList = res.data
					let arr = []
					arr = res.data.map(item => item.address);
					getSecondAddress(res.data[0].id).then(res => {
						this.columnData = res.data.map(item => (item.address))
						this.columns = [arr, [...this.columnData]]
						this.loading = false
					})
				})
			},

			//获取二级辖区列表
			getSecondAddress(id) {
				getSecondAddress(id).then(res => {
					this.columnData = res.data.map(item => (item.address))
					this.columns = [arr, [...this.columnData]]
					this.loading = false
				})
			},

			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					this.loading = true
					if (index === 0) {
						this.loading = false
					} else {
						let targetObject = this.locationList.find(obj => obj.address === this.columns[0][index]);
						// 如果找到了具有匹配 name 属性值的对象，则获取其 id 属性值
						if (targetObject) {
							let idValue = targetObject.id;
							console.log(idValue)
							getSecondAddress(idValue).then(res => {
								console.log(res)
								this.columnData = res.data.map(item => (item.address))
								this.loading = false
								picker.setColumnValues(1, this.columnData)
							})
						}
					}
				}
			},

			// 回调参数为包含columnIndex、value、values
			confirm(e) {
				var that = this
				this.form.select = e.value[0] + '/' + e.value[1]
				this.form.firstAddress = e.value[0]
				this.form.secondAddress = e.value[1]
				uni.showModal({
					title: '提示',
					content: '确认分配于' + this.form.firstAddress + "/" + this.form.secondAddress,
					success: (res) => {
						if (res.confirm) {
							console.log(that.form.adviseId, that.form.firstAddress, that.form
								.secondAddress)
							sentAddress(that.form.adviseId, that.form.firstAddress, that.form
								.secondAddress).then(res => {
								console.log(JSON.stringify(res))
								if (res.code === 200) {
									uni.showToast({
										title: "分配成功"
									})
									that.show = false
								} else {
									uni.showToast({
										title: "分配失败"
									})
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},

			cancel(e) {
				this.show = false
			},

			handleSelect(res) {
				const baseUrl = config.imagePrefix
				console.log(baseUrl)
				uni.uploadFile({
					url: baseUrl + '/upload/localhost', //post请求的地址
					filePath: res.tempFiles[0].url,
					name: 'file',
					success: (uploadFileRes) => {
						//这里要注意，uploadFileRes.data是个String类型，要转对象的话需要JSON.parse一下
						var obj = JSON.parse(uploadFileRes.data);
						this.form.imgList.push(obj.data)
						this.form.imageValue.push({
							name: "file",
							extname: "png",
							url: obj.data,
						})

					}
				})
			},

			// 删除图片
			deletePic(event) {
				this.form.imageValue.splice(event.index, 1)
				this.form.imgList.splice(event.index, 1)
			},

			// 打开选择器
			openPicker() {
				this.show = true
			},

			//重新分配
			refresh() {
				// this.form.select = ''
				this.show = true
			},
			//上传结果
			submit() {
				this.$refs.form.validate().then(async res => {
					uploadResults(this.form.adviseId, this.form.content, this.form.phone, this.form.name, this
						.form.imgList).then(res => {
						console.log(res)
						if (res.code === 200) {
							uni.showToast({
								title: "上传成功",
								icon: 'success',
							})
							setTimeout(() => {
								uni.navigateBack()
							}, 500)
						}
					})
				}).catch(errors => {
					console.log(errors)
					uni.showToast({
						icon: 'error',
						title: '校验失败'
					})
				})
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form.setRules(this.rules)
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #f7f7f7;
	}

	.login-btn {
		height: 40px;
		font-size: 14px;
		line-height: 40px;
		width: 90%;
		justify-content: center;
		margin: 0 5%;
	}

	.fix-bottom {
		bottom: 3%;
		position: fixed;
		width: 100%;
	}
</style>